<?php
/*********************/
/*                   */
/*  后台订单模块       */
/*   BY voiet        */
/*   2009-11-26更新    */
/*                   */
/*********************/
//require_once( CORE_DIR."/model/trading/mdl.order.php" );
class cmd_order extends mdl_order
{
	function searchoptions( )
	{
		return array( "order_id" => "订单号", "bn" => "货号", "logi_no" => "物流单号", "member_name" => "会员用户名", "ship_name" => "收货人姓名", "ship_addr" => "收货人地址", "ship_tel" => "收货人电话", "mark_text" => "订单备注", "memo" => "订单附言", "refer_id" => "来源ID" );
	}
	
	function batchupdatearray( $goods_id, $tableName, $updateName, $updateValue )
	{
		$addSql = array( );
		foreach ( $updateName as $k => $v )
		{
			$addSql[] = $v." = \"".$updateValue[$k]."\" ";
		}
		$sql = "UPDATE ".$tableName." SET ".implode( ",", $addSql )." WHERE order_id in (".implode( ",", $goods_id ).") ";

		$this->db->exec( $sql );
		return true;
	}

	
	function getfilter( $p )
	{
		$delivery = $this->system->loadmodel( "trading/delivery" );
		$return['areas'] = $delivery->getdlarealist( );
		$return['delivery'] = $delivery->getdltypelist( );
		$payment = $this->system->loadmodel( "trading/payment" );
		$return['payment'] = $payment->getmethods( );
		$modTag = $this->system->loadmodel( "system/tag" );
		$return['tags'] = $modTag->taglist( "order" );
		return $return;
	}
	
	function _filter( $filter )
	{
		$where = array( 1 );
		if ( is_array( $filter['ordertype'] ) )
		{
			foreach ( $filter['ordertype'] as $ordertype )
			{
				if ( $ordertype != "_ANY_" )
				{
					$aOrdertype[] = $ordertype;
				}
				if ( 0 < count( $aOrdertype ) )
				{
					$where[] = "ordertype in ('".implode( $aOrdertype, "','" )."')";
				}
			}
			unset( $filter['ordertype']);
		}
		if ( is_array( $filter['status'] ) )
		{
			foreach ( $filter['status'] as $state )
			{
				if ( $state != "_ANY_" )
				{
					$aState[] = $state;
				}
				if ( 0 < count( $aState ) )
				{
					$where[] = "status in ('".implode( $aState, "','" )."')";
				}
			}
			unset( $filter['status']);
		}
		if ( is_array( $filter['pay_status'] ) )
		{
			foreach ( $filter['pay_status'] as $paystate )
			{
				if ( $paystate !== "_ANY_" )
				{
					$aPaystate[] = intval( $paystate );
				}
			}
			if ( 0 < count( $aPaystate ) )
			{
				$where[] = "pay_status IN (".implode( $aPaystate, "," ).")";
			}
			unset( $filter['pay_status']);
		}
		if ( is_array( $filter['ship_status'] ) )
		{
			foreach ( $filter['ship_status'] as $shipstate )
			{
				if ( $shipstate !== "_ANY_" )
				{
					$aShipstate[] = intval( $shipstate );
				}
			}
			if ( 0 < count( $aShipstate ) )
			{
				$where[] = "ship_status IN (".implode( $aShipstate, "," ).")";
			}
			unset( $filter['ship_status']);
		}
		if ( is_array( $filter['areas'] ) )
		{
			foreach ( $filter['areas'] as $area )
			{
				if ( $area != "_ANY_" )
				{
					$aArea[] = "shipping_area = \"".$area."\"";
				}
			}
			if ( 0 < count( $aArea ) )
			{
				$where[] = "(".implode( $aArea, " OR " ).")";
			}
			unset( $filter['areas']);
		}
		if ( is_array( $filter['delivery'] ) )
		{
			foreach ( $filter['delivery'] as $delivery )
			{
				if ( $delivery != "_ANY_" )
				{
					$aDelivery[] = "shipping_id = ".intval( $delivery );
				}
			}
			if ( 0 < count( $aDelivery ) )
			{
				$where[] = "(".implode( $aDelivery, " OR " ).")";
			}
			unset( $filter['delivery']);
		}
		if ( is_array( $filter['payment'] ) )
		{
			foreach ( $filter['payment'] as $payment )
			{
				if ( $payment != "_ANY_" )
				{
					$aPayment[] = "payment = ".intval( $payment );
				}
			}
			if ( 0 < count( $aPayment ) )
			{
				$where[] = "(".implode( $aPayment, " OR " ).")";
			}
			unset( $filter['payment']);
		}
		if ( is_array( $filter['tag'] ) )
		{
			foreach ( $filter['tag'] as $tag )
			{
				if ( $tag != "_ANY_" )
				{
					$aTag[] = intval( $tag );
				}
			}
			if ( 0 < count( $aTag ) )
			{
				foreach ( $this->db->select( "SELECT rel_id FROM sdb_tag_rel r\n                    LEFT JOIN sdb_tags t ON r.tag_id=t.tag_id\n                    WHERE t.tag_type = 'order' AND r.tag_id IN(".implode( ",", $aTag ).")" ) as $rows )
				{
					$filter['order_id'][] = $rows['rel_id'];
				}
				if ( empty( $filter['order_id'] ) )
				{
					$filter['order_id'][] = -1;
				}
			}
			$filter['tag'] = null;
		}
		if ( isset( $filter['order_id'] ) )
		{
			if ( is_array( $filter['order_id'] ) )
			{
				if ( !isset( $filter['order_id'][1] ) )
				{
					$where[] = "order_id LIKE '".$filter['order_id'][0]."%'";
				}
				else
				{
					$aOrder = array( );
					foreach ( $filter['order_id'] as $order_id )
					{
						$aOrder[] = "order_id=\"".$order_id."\"";
					}
					$where[] = "(".implode( " OR ", $aOrder ).")";
					unset( $aOrder );
				}
			}
			else
			{
				$where[] = "order_id LIKE '".$filter['order_id']."%'";
			}
			unset( $filter['order_id']);
		}
		if ( isset( $filter['bn'] ) && $filter['bn'] !== "" )
		{
			$aId = array( 0 );
			foreach ( $this->db->select( "SELECT order_id FROM sdb_order_items WHERE bn LIKE '".$filter['bn']."%'" ) as $rows )
			{
				$aId[] = "order_id = '".$rows['order_id']."'";
			}
			$where[] = "(".implode( " OR ", $aId ).")";
			unset( $filter['bn']);
		}
		if ( isset( $filter['goods_name'] ) && $filter['goods_name'] !== "" )
		{
			$aId = array( 0 );
			foreach ( $this->db->select( "SELECT order_id FROM sdb_order_items WHERE name LIKE '%".$filter['goods_name']."%'" ) as $rows )
			{
				$aId[] = "order_id = '".$rows['order_id']."'";
			}
			$where[] = "(".implode( " OR ", $aId ).")";
			unset( $filter['goods_name']);
		}
		if ( isset( $filter['logi_no'] ) && $filter['logi_no'] !== "" )
		{
			$objShipping = $this->system->loadmodel( "trading/shipping" );
			$aOrder = $objShipping->getordersbylogino( $filter['logi_no'] );
			$where[] = "order_id IN ('".implode( "','", $aOrder )."')";
		}
		if ( isset( $filter['ship_name'] ) )
		{
			$where[] = "ship_name LIKE '%".$filter['ship_name']."%'";
			unset( $filter['ship_name']);
		}
		if ( isset( $filter['createtime'] ) )
		{
			$where[] = "createtime > '".$filter['createtime']."'";
			unset( $filter['createtime']);
		}
		if ( isset( $filter['ship_addr'] ) )
		{
			$where[] = "ship_addr LIKE '%".$filter['ship_addr']."%'";
			unset( $filter['ship_addr']);
		}
		if ( isset( $filter['ship_tel'] ) )
		{
			$where[] = "ship_tel LIKE '%".$filter['ship_tel']."%'";
			unset( $filter['ship_tel']);
		}
		if ( isset( $filter['member_name'] ) && $filter['member_name'] !== "" )
		{
			$aId = array( 0 );
			foreach ( $this->db->select( "SELECT member_id FROM sdb_members WHERE uname = '".$filter['member_name']."'" ) as $rows )
			{
				$aId[] = $rows['member_id'];
			}
			$where[] = "member_id IN (".implode( ",", $aId ).")";
			unset( $filter['member_name']);
		}
		if ( isset( $filter['return_order_id'] ) && $filter['return_order_id'] != "" )
		{
			$where[] = "order_id like \"".$filter['return_order_id']."%\"";
			unset( $filter['return_order_id']);
		}
		if ( isset( $filter['mark_text'] ) )
		{
			$where[] = "mark_text LIKE '%".$filter['mark_text']."%'";
			unset( $filter['mark_text']);
		}
		if ( isset( $filter['memo'] ) )
		{
			$where[] = "memo LIKE '%".$filter['memo']."%'";
			unset( $filter['memo']);
		}
		if ( isset( $filter['refer_id'] ) )
		{
			$where[] = "refer_id LIKE '".$filter['refer_id']."%'";
			unset( $filter['refer_id']);
		}
				
		if ( $filter['mincreatetime'] && $filter['maxcreatetime'] )
		{
			$where[] = " (createtime>=".strtotime( $filter['mincreatetime'] )." AND createtime<=".strtotime( $filter['maxcreatetime']." 23:59:59" ).") ";
		}
		else if ( $filter['mincreatetime'] )
		{
			$where[] = "createtime>=".strtotime( $filter['mincreatetime'] );
		}
		else if ( $filter['maxcreatetime'] )
		{
			$where[] = "createtime<=".strtotime( $filter['maxcreatetime']." 23:59:59" );
		}
		if ( $filter['minmoney'] && $filter['maxmoney'] )
		{
			if ( $filter['minmoney'] == $filter['maxmoney'] )
			{
				$where[] = "final_amount=".$filter['minmoney'];
			}
			else if ( $filter['minmoney'] < $filter['maxmoney'] )
			{
				$where[] = " (final_amount>=".$filter['minmoney']." AND final_amount<=".$filter['maxmoney'].") ";
			}
		}
		else if ( $filter['minmoney'] )
		{
			$where[] = "final_amount>=".$filter['minmoney'];
		}
		else if ( $filter['maxmoney'] )
		{
			$where[] = "final_amount<=".$filter['maxmoney'];
		}
		return shopobject::_filter( $filter )." and ".implode( $where, " AND " );
	}
	
	
	function tochangepay( $orderid )
	{
			$aRet = $this->getfieldbyid( $orderid, array( "status", "pay_status", "ship_status" ) );
			if ( $aRet['pay_status'] == 1 || $aRet['pay_status'] == 2)
			{
					$sqlString = "UPDATE sdb_orders SET pay_status = 3,last_change_time='".time( )."' WHERE order_id = '".$orderid."'";
					$this->db->exec( $sqlString );
					$this->_info['order_id'] = $orderid;
					$this->addlog( "订单恢复部分付款状态", $this->op_id ? $this->op_id : null, $this->op_name ? $this->op_name : null, "改变付款状态" );
					
					return true;
			}
			else
			{
					$message = __( "操作失败: 订单状态锁定" );
					return false;
			}
	}
	
	
	function toresumepay( $orderid )
	{
			$aRet = $this->getfieldbyid( $orderid, array( "status", "pay_status", "ship_status" ) );
			if ( $aRet['pay_status'] == 3 || $aRet['pay_status'] == 2 || $aRet['pay_status'] == 4 )
			{
					$sqlString = "UPDATE sdb_orders SET pay_status = 1,last_change_time='".time( )."' WHERE order_id = '".$orderid."'";
					$this->db->exec( $sqlString );
					$this->_info['order_id'] = $orderid;
					$this->addlog( "订单恢复已付款状态", $this->op_id ? $this->op_id : null, $this->op_name ? $this->op_name : null, "改变付款状态" );
					
					return true;
			}
			else
			{
					$message = __( "操作失败: 订单状态锁定" );
					return false;
			}
	}
	
	
	function tochangeship( $orderid )
	{
			$aRet = $this->getfieldbyid( $orderid, array( "status", "pay_status", "ship_status" ) );
			if ( $aRet['ship_status'] == 1 )
			{
					$sqlString = "UPDATE sdb_orders SET ship_status = 2,last_change_time='".time( )."' WHERE order_id = '".$orderid."'";
					$this->db->exec( $sqlString );
					$this->_info['order_id'] = $orderid;
					$this->addlog( "订单恢复部分发货状态", $this->op_id ? $this->op_id : null, $this->op_name ? $this->op_name : null, "改变发货状态" );
					
					return true;
			}
			else
			{
					$message = __( "操作失败: 订单状态锁定" );
					return false;
			}
	}
	
	
	function toresumeship( $orderid )
	{
			$aRet = $this->getfieldbyid( $orderid, array( "status", "pay_status", "ship_status" ) );
			if ( $aRet['ship_status'] == 2 || $aRet['ship_status'] == 3 )
			{
					$sqlString = "UPDATE sdb_orders SET ship_status = 1,last_change_time='".time( )."' WHERE order_id = '".$orderid."'";
					$this->db->exec( $sqlString );
					$this->_info['order_id'] = $orderid;
					$this->addlog( "订单恢复已发货状态", $this->op_id ? $this->op_id : null, $this->op_name ? $this->op_name : null, "改变发货状态" );
					
					return true;
			}
			else
			{
					$message = __( "操作失败: 订单状态锁定" );
					return false;
			}
	}
	
	
	function getconsignid( $order_no )
	{
			$sql = "select delivery_id from sdb_delivery where order_id ='{$order_no}'";
			return $this->db->select( $sql );
	}
	
	function dotogether( $mainorderid,$suborderid,$data,$shipstate=0,&$message)
	{
			if(!$mainorderid || !$suborderid){
				$message = __( "订单号错误或不存在" );
				return false;
				
			}
			
			$sqlString = "UPDATE sdb_order_items SET order_id = '".$mainorderid."' WHERE order_id = '".$suborderid."'";
			$this->db->exec( $sqlString );
			
			
			$aRs = $this->db->query( "SELECT * FROM sdb_orders WHERE order_id = ".$mainorderid);
			//unset( $aRs['order_id'] );
			$sSql = $this->db->getupdatesql( $aRs, $data );
			
			$ssqlString = "UPDATE sdb_orders SET disabled = 'true' WHERE order_id = '".$suborderid."'";
			$this->db->exec( $ssqlString );
			if ( !$sSql || $this->db->exec( $sSql ) )
			{
					$this->_info['order_id'] = $mainorderid;
					$this->addlog( "合并订单".$suborderid, $this->op_id ? $this->op_id : null, $this->op_name ? $this->op_name : null, "合并" );
					$message = __( "订单合并成功" );
					return true;	
			}
			else
			{
					return false;
			}
					
	}
	
	function create( &$aCart, &$aMember, &$aDelivery, &$aPayment, &$minfo, &$postInfo )
	{
			$oSale = $this->system->loadmodel( "trading/sale" );
			$trading = $oSale->getcartobject( $aCart, $aMember['member_lv_id'], true, true );
			
			$this->_saveaddr( $aMember['member_id'], $aDelivery );
			$iProduct = 0;
			if ( is_array( $trading['products'] ) && count( $trading['products'] ) )
			{
					$objGoods = $this->system->loadmodel( "trading/goods" );
					$arr = array( );
					$aLinkId = array( );
					foreach ( $trading['products'] as $k => $p )
					{
							$aStore = $objGoods->getfieldbyid( $p['goods_id'], array( "marketable", "disabled" ) );
							if ( $aStore['marketable'] == "false" || $aStore['disabled'] == "true" )
							{
									trigger_error( $p['name']."商品未发布不能下单。", E_USER_ERROR );
									return false;
									exit( );
							}
							$arr[] = $p['name']."(".$p['nums'].")";
							$this->itemnum += $p['nums'];
							$aLinkId[] = $p['goods_id'];
							$trading['products'][$k]['addon']['minfo'] = $minfo[$p['product_id']];
							$trading['products'][$k]['minfo'] = $minfo[$p['product_id']];
							if ( $p['goods_id'] )
							{
									$aP[] = $p['goods_id'];
							}
							++$iProduct;
					}
			}
			if ( $trading['package'] || $trading['gift_e'] )
			{
					$otherPhysical = true;
			}
			else
			{
					$otherPhysical = false;
			}
			if ( count( $aP ) || $otherPhysical )
			{
					$return = $this->checkorderdelivery( $aP, $aDelivery, $otherPhysical, $aMember['member_id'] );
					if ( $return )
					{
							$aDelivery['is_delivery'] = $return;
							if ( $return == "Y" && empty( $aDelivery['shipping_id'] ) )
							{
									trigger_error( "提交不成功，请选择配送方式", E_USER_ERROR );
									return false;
									exit( );
							}
					}
					else
					{
							trigger_error( "对不起，请完整填写配送信息", E_USER_ERROR );
							return false;
							exit( );
					}
			}
			$iPackage = 0;
			if ( is_array( $trading['package'] ) && count( $trading['package'] ) )
			{
					$objCart = $this->system->loadmodel( "trading/cart" );
					foreach ( $trading['package'] as $v )
					{
							if ( !$objCart->_checkstore( $v['goods_id'], $v['nums'] ) )
							{
										trigger_error( "捆绑商品库存不足", E_USER_ERROR );
										return false;
										exit( );
							}
							++$iPackage;
							$arr[] = $v['name']."(".$v['nums'].")";
					}
			}
			if ( is_array( $trading['gift_e'] ) && count( $trading['gift_e'] ) )
			{
					foreach ( $trading['gift_e'] as $v )
					{
							$arr[] = $v['name']."(".$v['nums'].")";
					}
			}
			if ( $iProduct + $iPackage + count( $trading['gift_p'] ) + count( $trading['gift_e'] ) == 0 )
			{
					trigger_error( "购物车中无有效商品!", E_USER_ERROR );
					return false;
			}
			$oCur = $this->system->loadmodel( "system/cur" );
			$tdelivery = explode( ":", $aDelivery['ship_area'] );
			$area_id = $tdelivery[count( $tdelivery ) - 1];
			$oDelivery = $this->system->loadmodel( "trading/delivery" );
			$rows = $oDelivery->getdltypebyarea( $area_id, $trading['weight'], $aDelivery['shipping_id'] );
			
			$trading['weight_cn'] = $postInfo['weight_cn'] ? $postInfo['weight_cn'] : 0;
			$trading['weight_kr'] = $postInfo['weight_kr'] ? $postInfo['weight_kr'] : 0;
			if ( $trading['exemptFreight'] == 1 )
			{
					$aDelivery['cost_freight'] = 0;
			}
			else
			{
					//2009-11-26 voiet 更新运费
				if($trading['weight_cn']>0 && $trading['weight_kr']>0)
				{
					if($aDelivery['shipping_id']==15)$aShip_cn = $oDelivery->getdltypebyarea( $area_id, $trading['weight_cn'], 3 );
					elseif($aDelivery['shipping_id']==16)$aShip_cn = $oDelivery->getdltypebyarea( $area_id, $trading['weight_cn'], 2 );
					elseif($aDelivery['shipping_id']==17)$aShip_cn = $oDelivery->getdltypebyarea( $area_id, $trading['weight_cn'], 1 );
					else $aShip_cn = $oDelivery->getdltypebyarea( $area_id, $trading['weight_cn'], 13 );
					$trading['cost_freight_cn'] = cal_fee( $aShip_cn[0]['expressions'], $trading['weight_cn'], $trading['pmt_b']['totalPrice'], $aShip_cn[0]['price'] );
					$trading['cost_freight_kr'] = cal_fee( $rows[0]['expressions'], $trading['weight_kr'], $trading['pmt_b']['totalPrice'], $rows[0]['price'] );
					$trading['cost_freight'] = $trading['cost_freight_cn'] + $trading['cost_freight_kr'];
				}
				else
				{
					$trading['cost_freight'] = cal_fee( $rows[0]['expressions'], $trading['weight'], $trading['pmt_b']['totalPrice'], $rows[0]['price'] );
					if($trading['weight_kr']>0)$trading['cost_freight_kr'] = $trading['cost_freight'];
					else $trading['cost_freight_cn']=$trading['cost_freight'];
					
				}
				
				//2009-11-26 voiet 更新个别分销商的运费
				if($aDelivery['shipping_id'] == 13){
					if($aMember['member_id'] == 2161 || $aMember['member_id'] == 2204 || $aMember['member_id'] == 6166 )
						$trading['cost_freight'] = 0;
					elseif($aMember['member_id']==6318)$trading['cost_freight'] = 10;
				}
					
				$trading['cost_freight'] = $oCur->formatnumber( $trading['cost_freight'] );
			}
			
			$trading['cost_freight'] = is_null( $trading['cost_freight'] ) ? 0 : $trading['cost_freight'];
			$trading['cost_freight_kr'] = is_null( $trading['cost_freight_kr'] ) ? 0 : $trading['cost_freight_kr'];
			$trading['cost_freight_cn'] = is_null( $trading['cost_freight_cn'] ) ? 0 : $trading['cost_freight_cn'];
			
			
			if ( $aDelivery['is_protect'][$aDelivery['shipping_id']] && $rows[0]['protect'] == 1 )
			{
					$aDelivery['cost_protect'] = $oCur->formatnumber( max( $trading['totalPrice'] * $rows[0]['protect_rate'], $rows[0]['minprice'] ) );
					$aDelivery['is_protect'] = "true";
			}
			else
			{
					$aDelivery['cost_protect'] = 0;
					$aDelivery['is_protect'] = "false";
			}
			if ( 0 < $aPayment['payment'] || $aPayment['payment'] == -1 )
			{
					$oPayment = $this->system->loadmodel( "trading/payment" );
					$aPay = $oPayment->getpaymentbyid( $aPayment['payment'] );
					if ( $aPay['pay_type'] == "DEPOSIT" && $aMember['member_id'] == "" )
					{
							trigger_error( "未登录客户不能选择预存款支付!", E_USER_ERROR );
							return false;
					}
					$aPayment['fee'] = $aPay['fee'];
			}
			else
			{
					trigger_error( "提交不成功，未选择支付方式!", E_USER_ERROR );
					return false;
			}
			$currency = $oCur->getcur( $aPayment['currency'] );
			if ( !$this->checkpoint( $aMember['member_id'], $trading ) )
			{
					return false;
			}
			if ( !$this->checkgift( $trading['gift_p'] ) )
			{
					return false;
			}
			$orderInfo = $trading;
			$orderInfo['order_id'] = $this->gen_id( );
			$orderInfo['cur_rate'] = 0 < $currency['cur_rate'] ? $currency['cur_rate'] : 1;
			$orderInfo['tostr'] = addslashes( implode( ",", $arr ) );
			$orderInfo['itemnum'] = $this->itemnum;
			//2009-11-26 voiet 更新会员等级、批发积分、和类别
			$orderInfo['member_lv_id'] = $aMember['member_lv_id'];
			if($aMember['member_lv_id']>=4)$orderInfo['totalGainScore'] = 0;
			//$orderInfo['weight_cn'] = $trading['weight_kr'];
			//$orderInfo['weight_kr'] = $trading['weight_kr'];
			if($trading['weight_cn']>0 && $trading['weight_kr']>0)$orderInfo['ordertype']='cnkr';
			elseif($trading['weight_kr']>0)$orderInfo['ordertype']='kr';
			else $orderInfo['ordertype']='cn';
			
			getrefer( $orderInfo );
			$aDelivery['ship_time'] = ( $aDelivery['day'] == "specal" ? $aDelivery['specal_day'] : $aDelivery['day'] )." ".$aDelivery['time'];
			$orderInfo = array_merge( $orderInfo, $aDelivery, $aPayment );
			if ( $aMember )
			{
					$orderInfo = array_merge( $orderInfo, $aMember );
			}
			return $this->save( $orderInfo, true, $postInfo );
	}
	
	//获得收益订单
	function fetchbyrefer( $member_id, $nPage )
	{
		return $this->db->select_f( "select * from sdb_orders where disabled=\"false\" AND member_id != ".intval($member_id)." AND member_lv_id < 4 AND refer_id='prem|".$member_id."' order by acttime desc", $nPage, PERPAGE );
	}
	
	
	

}

?>